package com.freedom.auth.service.impl;

import com.freedom.auth.service.ILoginService;
import com.freedom.auth.vo.LoginVO;
import com.freedom.base.context.LoginContext;
import com.freedom.org.domain.Employee;
import com.freedom.org.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.UUID;

/**
 * @author freedom
 */
@Service
public class LoginServiceImpl implements ILoginService {
    @Autowired
    private IEmployeeService service;

    @Override
    public LoginVO login ( Employee employee ) {
        // 数据判空
        if (Objects.isNull(employee.getUsername()) || Objects.isNull(employee.getPassword())) {
            throw new RuntimeException("数据为空");
        }
        // 根据账户查对象
        Employee user = service.getByName(employee);
        // 判断账号是否为空
        if (Objects.isNull(user)) {
            throw new RuntimeException("账户为空");
        }
        // 判断密码是否正确
        if (!user.getPassword().equals(employee.getPassword())) {
            throw new RuntimeException("密码不正确");
        }
        // 生成UUID返回
        String token = UUID.randomUUID().toString();
        // 将用户信息存全局map  以后存redis
        LoginContext.loginMap.put(token, user);
        LoginVO loginVO = new LoginVO();
        loginVO.setToken(token);
        // 要进行数据脱敏
        user.setPassword(null);
        loginVO.setUser(user);
        return loginVO;
    }
}
